﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Organizations;
using Abp.Runtime.Caching;
using AVISOutBound.SSOServer.Authorization.Roles;
using System.Threading.Tasks;

namespace AVISOutBound.SSOServer.Authorization.Users
{
    public class UserManager : AbpUserManager<Role, User>
    {
        private readonly UserStore _userStore;
        public UserManager(
            RoleManager roleManager,
            UserStore userStore, 
            IOptions<IdentityOptions> optionsAccessor, 
            IPasswordHasher<User> passwordHasher, 
            IEnumerable<IUserValidator<User>> userValidators, 
            IEnumerable<IPasswordValidator<User>> passwordValidators,
            ILookupNormalizer keyNormalizer, 
            IdentityErrorDescriber errors, 
            IServiceProvider services, 
            ILogger<UserManager<User>> logger, 
            IPermissionManager permissionManager, 
            IUnitOfWorkManager unitOfWorkManager, 
            ICacheManager cacheManager, 
            IRepository<OrganizationUnit, long> organizationUnitRepository, 
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, 
            IOrganizationUnitSettings organizationUnitSettings, 
            ISettingManager settingManager)
            : base(
                roleManager,
                userStore, 
                optionsAccessor, 
                passwordHasher, 
                userValidators, 
                passwordValidators, 
                keyNormalizer, 
                errors, 
                services, 
                logger, 
                permissionManager, 
                unitOfWorkManager, 
                cacheManager,
                organizationUnitRepository, 
                userOrganizationUnitRepository, 
                organizationUnitSettings, 
                settingManager)
        {
            _userStore = userStore;
        }
        public virtual Task<User> FindByNameOrEmailAsyncByPhone(int? tenantId, string phone)
        {
            return _userStore.FindByNameOrEmailAsyncByPhone(tenantId, phone);
        }
        public virtual async Task<IdentityResult> ChangePasswordAsyncBySmsCode(User user, string newPassword)
        {
            var hash = newPassword != null ? PasswordHasher.HashPassword(user, newPassword) : null;
            user.Password = hash;
            return await _userStore.UpdateAsync(user);
        }
    }
}
